package fileutil

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
)

// 移除系统文件
func DealDesktop(path string, fileName string) bool {
	if fileName == "desktop.ini" {
		err := os.Remove(filepath.Join(path, fileName))
		if err == nil {
			fmt.Println("desktop.ini 文件删除成功！")
		} else {
			fmt.Println("desktop.ini 删除错误")
		}
		return true
	} else {
		return false
	}
}

func IsExist(fileFullPath string) bool {
	_, err := os.Stat(fileFullPath)
	return err == nil || os.IsExist(err)
}

func IsFile(fileFullPath string) bool {
	stat, err := os.Stat(fileFullPath)

	return err == nil && !stat.IsDir()
}

func MoveFiles(fileNames []string, srcPath, dstPath string) (int, int) {
	success := 0
	fail := 0
	dstDirName := path.Base(dstPath)
	for _, fileName := range fileNames {
		err := os.Rename(filepath.Join(srcPath, fileName), filepath.Join(dstPath, fileName))
		if err == nil {
			success++
			fmt.Printf("%s 被移动到 %s\n", fileName, dstDirName)
		} else {
			fail++
			fmt.Printf("%s 无法移动\n", fileName)
		}
	}
	return success, fail
}

func CopyFiles(fileNames []string, srcPath, dstPath string) (int, int) {
	success := 0
	fail := 0
	dstDirName := path.Base(dstPath)
	for _, fileName := range fileNames {
		err := CopyFile(fileName, srcPath, dstPath)
		if err == nil {
			success++
			fmt.Printf("%s 被复制到 %s\n", fileName, dstDirName)
		} else {
			fail++
			fmt.Printf("%s 无法复制\n", fileName)
		}
	}
	return success, fail
}

// 复制单个文件
func CopyFile(fileName string, srcPath, dstPath string) error {
	src, _ := os.Open(filepath.Join(srcPath, fileName))
	dst, _ := os.Create(filepath.Join(dstPath, fileName))
	defer src.Close()
	defer dst.Close()
	_, err := io.Copy(dst, src)
	return err
}

func MkDir(fatherPath string, dirName string) (string, error) {
	dirPath := path.Join(fatherPath, dirName)
	err := os.MkdirAll(dirPath, os.ModePerm)
	return dirPath, err
}

func GetInputLine(scanner *bufio.Reader, msg string) (string, error) {
	fmt.Println(msg)
	line, _, err := scanner.ReadLine()
	return string(line), err
}
